let mongoose = require('mongoose');

let schema = new mongoose.Schema({
    count:{ //未领取次数
        type:Number,
        default:3
    },
    receiveCount:{  //已领取次数
        type:Number,
        default:0
    },
    lastRefreshTick:{ //最后刷新时间戳
        type:Number,
        default:0
    }
});

let config=[
    [{type:2,count:100}],
    [{type:1,count:50}],
    [{type:201,count:5},{type:202,count:5}]
];

schema.methods={
    getMessage(){
        this._refresh();
        return {
            count:this.count,
            receiveCount:this.receiveCount,
            rewards:config
        };
    },
    getGiftsCount(){
        return this.count-this.receiveCount;
    },
    _copyRewards(rewards){
        let result=[];
        rewards.forEach(reward=>{
            result.push({
                type:reward.type,
                count:reward.count
            })
        });
        return result;
    },
    //领取
    receive(options){
        if(this.receiveCount>=this.count){
            throw new Error('您今天的每日礼包已经领取完了，请明天再来，谢谢！');
        }
        let rewards=this._copyRewards(config[this.receiveCount]);
        options.self.getGoods(rewards);
        this.receiveCount++;
        return rewards;
    },
    //刷新每日礼包
    _refresh(){
        //let now=new Date().getTime()-21600000;
        let nowDate=new Date();
        let lastDate=new Date(this.lastRefreshTick);
        if(nowDate.toLocaleDateString()!==lastDate.toLocaleDateString()){
            this.count=3;
            this.receiveCount=0;
            this.lastRefreshTick=new Date().getTime();
        }
    }
};

module.exports = schema;